$(document).ready(() => {
  const add = new bootstrap.Modal($(`.add-modal`)[0]);
  const edit = new bootstrap.Modal($(`.edit-modal`)[0]);
  const creator = `无奈又`;
  function rendering() {
    $.get(`https://hmajax.itheima.net/api/books`, { creator }, (e) => {
      let str = e.data.map((item, i) => {
        const { id, bookname, author, publisher } = item
        return `<tr>
        <td>${i + 1}</td>
        <td>${bookname}</td>
        <td>${author}</td>
        <td>${publisher}</td>
        <td data-id=${id}>
          <span class="del">删除</span>
          <span class="edit">编辑</span>
        </td>
      </tr>`
      }).join(``)
      $(`.list`)[0].innerHTML = str
    }).fail(e => console.log(e))
  }
  rendering()
  $(`.add-btn`).click(addchange)
  function addchange() {
    const book = {
      bookname: $(`.add-form .bookname`)[0].value,
      author: $(`.add-form .author`)[0].value,
      publisher: $(`.add-form .publisher`)[0].value
    }
    $.post(`https://hmajax.itheima.net/api/books`, { creator, ...book, }, (e) => {
      rendering();
      $(`.add-form`)[0].reset()
      add.hide()
    })
  }
  $(`.list`).click(e => {
    change(e)
  })
  function change(e) {
    let father = e.target.closest(`td`).dataset.id;
    if (e.target.classList.contains(`del`)) {
      $.ajax({
        url: `https://hmajax.itheima.net/api/books/${father}`,
        method: `DELETE`,
        success: () => rendering(),
        erroe: e => console.log(e)
      })
    } else if (e.target.classList.contains(`edit`)) {
      edit.show()
      $.get(`https://hmajax.itheima.net/api/books/${father}`, e => {
        const { id, bookname, author, publisher } = e.data
        $(`.edit-form .id`)[0].value=id
        $(`.edit-form .bookname`)[0].value = bookname
        $(`.edit-form .author`)[0].value = author
        $(`.edit-form .publisher`)[0].value = publisher
        $(`.edit-btn`).click(editchange)
      })
    } else {
      return
    }
  }
  function editchange() {
    $.ajax({
      url:`https://hmajax.itheima.net/api/books/${$(`.edit-form .id`)[0].value}`,
      method:`PUT`,
      data:{
        bookname:$(`.edit-form .bookname`)[0].value,
        author:$(`.edit-form .author`)[0].value,
        publisher:$(`.edit-form .publisher`)[0].value,
        creator
      },
      success:()=>{
        edit.hide();
        rendering();
      }
    })
  }
})
